// pages/goods/goods-search/goods-search.js
const STORAGE_SEARCH_KEY = "searchRecords"
const MAX_PAGE_COUNT = 30

const FILTER_RECOMMEND = "recommend"
const FILTER_SALE_COUNT = "saleCount"
const FILTER_PRICE = "price"

var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
var emptyUtil = require('../../templates/empty/empty.js')
const app = getApp()
var that

Page({

  /**
   * 页面的初始数据
   */
  data: {
    identity:null,

    emptyParam: {
      emptyStatus: 0
    },
    isShowGoodsView: false, //是否显示商品列表 true:显示商品列表，false:显示搜索热词

    searchRecords: [], //搜素记录
    hotWordList: null, //搜索热词
    recommendwordList:null,//搜索推荐词

    cropListAll: [{
      "cropId": null,
      "cropName": "全部作物"
    }],
    cropListShow: ["全部作物"],
    cropListIndex: 0,

    goodsList: null, //商品列表
    requestGoodsTask: null, //请求task

    searchGoodParam: { //搜索条件
      "keyword": null,
      "cropId": null,
      "orderBy": FILTER_RECOMMEND,
      "sort": "desc",
      "pageNum": 0,
      "pageRows": MAX_PAGE_COUNT,
    },
    enableLoadMore: true,
    isLoadingMore: false,

    topInputValue: null, //输入的内容

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    this.getSearchRecord()
    this.requestHotWord()
    this.requestCropList()
    this.requestrecommendword()
    that.setData({
      identity:app.globalData.identity
    })
  },
  /**
   * 滑动到底部
   */
  onReachBottom: function() {
    this.requestGoodsList(this.data.searchGoodParam.keyword)
  },
  onShareAppMessage: function (res) {
    return util.handleShareApp()
  },
  /**
   * 添加商品进入购物车
   */
  addCartClick(e) {
    var goodId = e.currentTarget.dataset.goodid
    var skuId = e.currentTarget.dataset.skuid
    httpUtil.PostRequest("add_good_to_card", {
      goodId: goodId,
      skuId: skuId,
      buyCount: 1
    }, {
      success(res) {
        uiUtil.showToast("添加购物车成功")
        app.cartSelectsAdd(goodId, skuId)
      },
      fail(code, res) {
        uiUtil.showToast(res||"添加购物车失败")
      },
      complete() {}
    })
  },

  /**
   * 绑定输入事件
   */
  bindTopInput(e) {
    var value = e.detail.value
    this.setData({
      topInputValue: value
    })
  },

  /**
   * 搜索按钮点击
   */
  onSearchClick(e) {
    var keyword = e.detail.value;
    console.log("点击:" + keyword)
    if (keyword) {
      this.changeShowGoodsView(true)
      this.resetRequestParam()
      this.requestGoodsList(keyword)
      this.addSearchRecord(keyword)
    }
  },
  /**
   * 取消按钮点击
   */
  onCancelClick(e) {
    this.changeShowGoodsView(false)
    this.setData({
      topInputValue: null,
    })
  },
  /**
   * 关键词点击
   */
  onKeywordClick(e) {
    var keyword = e.currentTarget.dataset.name
    this.changeShowGoodsView(true)
    this.setData({
      topInputValue: keyword
    })
    this.requestGoodsList(keyword)
    this.addSearchRecord(keyword)
  },

  /**
   * 存储搜索记录
   */
  addSearchRecord(keyword) {
    var list = that.data.searchRecords || []
    var index = list.indexOf(keyword)
    if (index >= 0) {
      list.splice(index, 1);
    }
    list.unshift(keyword);
    list = list.slice(0, 15) //截取前15个
    that.setData({
      searchRecords: list
    })
    wx.setStorage({
      key: STORAGE_SEARCH_KEY,
      data: list,
    })
  },

  /**
   * 获取搜索记录
   */
  getSearchRecord() {
    var list = wx.getStorageSync(STORAGE_SEARCH_KEY) || []
    that.setData({
      searchRecords: list
    })
  },

  /**
   * 清空搜索记录
   */
  clearStorageSearch() {
    that.setData({
      searchRecords: []
    })
    wx.clearStorage()
  },
  /**
   * 获取搜索热词
   */
  requestHotWord() {
    httpUtil.PostRequest("search_hotword", {}, {
      success(res) {
        that.setData({
          hotWordList: res
        })
      },
      fail(code, res) {},
      complete() {}
    })
  },
  /**
   * 获取搜索推荐词
   */
  requestrecommendword() {
    httpUtil.PostRequest("search_recommendword", {}, {
      success(res) {
        that.setData({
          recommendwordList: res
        })
      },
      fail(code, res) { },
      complete() { }
    })
  },
  /**
   * 请求作物列表
   */
  requestCropList() {
    httpUtil.PostRequest("crop_list", {}, {
      success(res) {
        var listLength = res.length;

        var cropListAll = that.data.cropListAll
        var cropListShow = that.data.cropListShow
        if (listLength != 0) { //列表为空
          cropListAll = cropListAll.concat(res)
          for (var i = 0; i < listLength; i++) {
            var item = res[i]
            cropListShow.push(item.cropName)
          }
        }
        that.setData({
          cropListAll: cropListAll,
          cropListShow: cropListShow
        })
      },
      fail(code, res) {},
      complete() {}
    })
  },

  /**
   * 复位搜索条件
   */
  resetRequestParam(keyword) {
    this.setData({
      'searchGoodParam.pageNum': 0,
      'searchGoodParam.keyword': keyword,
      'searchGoodParam.sort': "desc",
      "searchGoodParam.orderBy": FILTER_RECOMMEND,
    })
  },
  changeShowGoodsView(isShowGoodsView) {
    this.setData({
      isShowGoodsView: isShowGoodsView
    })
  },

  /**
   * 获取商品列表
   */
  requestGoodsList(keyword) {
    var lastRequestTask = this.data.requestGoodsTask;
    if (lastRequestTask) {
      try {
        lastRequestTask.abort()
      } catch (e) {}
    }

    var curPage = that.data.searchGoodParam.pageNum
    if (curPage == 0) {
      that.setData({
        goodsList: [],
      })
    }
    if (curPage != 0 && (!that.data.enableLoadMore || that.data.isLoadingMore)) { //不可加载||正在加载
      return;
    }

    this.setData({
      isLoadingMore: true,
      'searchGoodParam.pageNum': curPage + 1,
      'searchGoodParam.keyword': keyword
    })
    var requestTask = httpUtil.PostRequest("search_goods_list", that.data.searchGoodParam, {
      complete() {
        wx.hideLoading()
        that.setData({
          isLoadingMore: false
        })
      },
      success(res) {
        var datalist;
        if (1 == that.data.searchGoodParam.pageNum) {
          datalist = res.goodList || []
          if (datalist.length == 0) { //内容为空
            emptyUtil.showEmptyView()
          } else {
            emptyUtil.hideView()
          }
        } else {
          datalist = that.data.goodsList.concat(res.goodList || [])
        }
        that.setData({
          goodsList: datalist,
          enableLoadMore: datalist.length < res.rowCount,
        })
      },
      fail(code, res) {
        that.setData({
          enableLoadMore: false,
        })
        if (1 == that.data.searchGoodParam.pageNum) { //内容为空
          var text = res || "获取商品信息失败"
          emptyUtil.showFailView(text)
        }
      }
    })
    that.setData({
      requestGoodsTask: requestTask
    })
  },

  /**
   * 筛选-推荐点击
   */
  filterRecommendClick() {
    var sort;
    if (this.data.searchGoodParam.orderBy = FILTER_RECOMMEND) { //切换查询顺序
      sort = this.data.searchGoodParam.sort;
      if (sort == 'desc') {
        sort = "asc"
      } else {
        sort = "desc"
      }
    } else {
      sort = 　'desc'
    }
    this.setData({
      'searchGoodParam.pageNum': 0,
      'searchGoodParam.sort': sort,
      "searchGoodParam.orderBy": FILTER_RECOMMEND,
    })
    this.requestGoodsList(this.data.searchGoodParam.keyword)
  },
  /**
   * 筛选-销量点击
   */
  filterSaleCountClick() {
    var sort;
    if (this.data.searchGoodParam.orderBy = FILTER_SALE_COUNT) { //切换查询顺序
      sort = this.data.searchGoodParam.sort;
      if (sort == 'desc') {
        sort = "asc"
      } else {
        sort = "desc"
      }
    } else {
      sort = 'desc'
    }
    this.setData({
      'searchGoodParam.pageNum': 0,
      'searchGoodParam.sort': sort,
      "searchGoodParam.orderBy": FILTER_SALE_COUNT,
    })
    this.requestGoodsList(this.data.searchGoodParam.keyword)
  },
  /**
   * 筛选-价格点击
   */
  filterPriceClick() {
    var sort;
    if (this.data.searchGoodParam.orderBy = FILTER_PRICE) { //切换查询顺序
      sort = this.data.searchGoodParam.sort;
      if (sort == 'desc') {
        sort = "asc"
      } else {
        sort = "desc"
      }
    } else {
      sort = 'desc'
    }
    this.setData({
      'searchGoodParam.pageNum': 0,
      'searchGoodParam.sort': sort,
      "searchGoodParam.orderBy": FILTER_PRICE,
    })
    this.requestGoodsList(this.data.searchGoodParam.keyword)
  },
  /**
   * 适用作物点击
   */
  filterCropClick(e) {
    var index = e.detail.value
    var cropId = this.data.cropListAll[index].cropId
    this.setData({
      'searchGoodParam.pageNum': 0,
      'searchGoodParam.cropId': cropId,
      cropListIndex: index
    })
    this.requestGoodsList(this.data.searchGoodParam.keyword)
  }
})